<template>
  <div class="el-select orgset-treeselect">
    <treeselect
      v-bind="$attrs"
      :options="orgSets"
      :searchable="true"
      :clearable="false"
      :disabled="!editable"
      :show-count="true"
      :disable-branch-nodes="false"
      :is-default-expanded="true"
      :normalizer="orgNormalizer"
      z-index="100"
      placeholder="选择组织机构"
      @select="orgSetSelect"
      v-on="$listeners"
    />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getUserInfo } from '@/utils/auth'
import { getPrivOrgSetByUserAccount } from '@/api/user'
import { getOrgSetsByCpyCode } from '@/api/system/orgSet'

export default {
  components: { Treeselect },
  props: {
    hasPriv: {
      type: Boolean,
      default: true,
      required: false
    },
    valueField: {
      type: String,
      default: 'orgCode',
      required: false
    },
    curOrgId: {
      type: String,
      default: null,
      required: false
    },
    editable: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  data() {
    return {
      orgSets: []
    }
  },
  computed: {
  },
  watch: {
    curOrgId: {
      handler(val) {
        // 获取所有组织机构
        getOrgSetsByCpyCode(val).then(res => {
          this.orgSets = res.data
        })
      }
    }
  },
  created() {
  },
  mounted() {
    this.refreshData()
  },
  methods: {
    orgNormalizer(node) {
      return {
        id: node[this.valueField],
        label: node.orgName
      }
    },
    orgSetSelect(node, instanceId) {
    },
    refreshData() {
      if (this.hasPriv) {
        const userInfo = getUserInfo()
        const cpycode = userInfo.cpyCode
        // 获取当前用户有权限的机构
        getPrivOrgSetByUserAccount(cpycode).then(res => {
          this.orgSets = res.data
        })
      } else {
        getOrgSetsByCpyCode(this.curOrgId).then(res => {
          this.orgSets = res.data
        })
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.orgset-treeselect{
  height: 26px;
  line-height: 26px;
  vertical-align: bottom;
}
::v-deep .vue-treeselect__control {
  line-height: 26px;
  height: 26px;
}
</style>
